package com.fangshi.viewmodels

import com.fangshi.api.ExitEnterGarageRequest
import com.fangshi.api.RemoteService

class GarageRepository(private val service: RemoteService) {
    suspend fun getGarages(): List<Area> {
        val response = service.getGarages()
        if (!response.success) {
            throw Exception(response.msg)
        }
        return response.data.areas.map { a -> Area(a) }
    }

    suspend fun getRecords(pageNo: Int, pageSize: Int): RecordWrapper {
        val response = service.getRecords(pageNo, pageSize)
        if (!response.success) {
            throw Exception(response.msg)
        }
        return RecordWrapper(response.data)
    }

    suspend fun addScanExitRecord(carCode: String, garageId: String) {
        addExitOrEntryRecord(garageId, carCode, Type.ScanExit)
    }

    suspend fun addScanEnterRecord(carCode: String, garageId: String) {
        addExitOrEntryRecord(garageId, carCode, Type.ScanEnter)
    }

    suspend fun addManualExitRecord(carCode: String, garageId: String) {
        addExitOrEntryRecord(garageId, carCode, Type.ManualExit)
    }

    suspend fun addManualEnterRecord(carCode: String, garageId: String) {
        addExitOrEntryRecord(garageId, carCode, Type.ManualEnter)
    }

    private suspend fun addExitOrEntryRecord(garageId: String, carCode: String, type: Type) {
        val response = service.exitOrEntry(ExitEnterGarageRequest(garageId, carCode, type.value))
        if (!response.success) {
            throw Exception(response.msg)
        }
    }

}

enum class Type(val value: String) {
    ScanEnter("1"),
    ScanExit("2"),
    ManualEnter("3"),
    ManualExit("4")
}

